#!/usr/bin/env python3
# -*- coding: utf-8 -*

from curses import wrapper
import curses
import subprocess

status = "nominal"


class Entry:
    def __init__(self, t, k="sth"):
        self.text = t
        self.key = k


def show_list(stdscr, l, selected=-1):
    global status
    maxline = curses.LINES - 2
    offset = 2
    stdscr.clear()
    start = max(0, selected - (maxline - offset))
    stdscr.addstr(0, 0, status, curses.A_REVERSE)
    j = 0
    for i in range(start, len(l)):
        e = l[i]
        stdscr.addstr(
            j + offset,
            0,
            e.key + ": " + e.text,
            curses.A_REVERSE if i == selected else curses.A_BOLD,
        )
        j += 1
        if j + offset > maxline:
            break
    stdscr.refresh()


def find_name(keystring):
    p = subprocess.Popen(
        'yt-dlp --get-title -s "ytsearch:' + keystring + '"',
        shell=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
    )
    res = ""
    lines = p.stdout.readlines()

    retval = p.wait()
    return lines[-1].decode("utf-8")


def download(sub):
    p = subprocess.Popen(
        'yt-dlp "ytsearch:' + sub.key + '"',
        shell=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
    )
    #    res = ''
    #    for line in p.stdout.readlines():
    #        res+=line.decode('utf-8').strip('\n')

    retval = p.wait()
    return


def main(stdscr):
    global status
    # Clear screen
    stdscr.clear()

    selected = 2
    file = open("subs")
    text = file.read()
    subs = text.split("\n")
    sublist = [Entry("", x) for x in subs if x != ""]
    show_list(stdscr, sublist)

    for s in sublist:
        s.text = find_name(s.key)
        show_list(stdscr, sublist, sublist.index(s))

    while True:
        show_list(stdscr, sublist, selected)

        ch = stdscr.getch()
        if ch == curses.KEY_DOWN:
            selected += 1
        elif ch == curses.KEY_UP:
            selected -= 1

        elif ch == 10:  # enter
            status = "Downloading"
            show_list(stdscr, sublist, selected)
            download(sublist[selected])
            status = "nominal"
            show_list(stdscr, sublist, selected)
        else:
            status = str(ch)

        # looping
        if selected == len(sublist):
            selected = 0
        elif selected == -1:
            selected = len(sublist) - 1


wrapper(main)
